package support

import (
	"encoding/json"
	"freechat-im/config"
	"freechat-im/model"
	"github.com/sirupsen/logrus"
	"github.com/streadway/amqp"
	"strconv"
)

var producer *MQProducer = &MQProducer{}

type MQProducer struct {
}

func GetMQProducer() *MQProducer {
	return producer
}

func (mq MQProducer) ToChangeMsgStatus(message model.MsgStatusChange) {
	messageJson, _ := json.Marshal(message) //序列化为json
	logrus.Info(">>> MQ发送消息到Queue["+config.MqStatusUpdate.QueueName+"] ... message = ", string(messageJson))

	err := config.GetMqChannel().Publish(config.MqStatusUpdate.Exchange, config.MqStatusUpdate.RoutingKey, false, false,
		amqp.Publishing{
			ContentType:  "application/json",                                                          // 消息内容的类型
			Body:         messageJson,                                                                 // 消息内容
			DeliveryMode: amqp.Persistent,                                                             // 消息持久化
			MessageId:    strconv.FormatInt(message.MsgId, 10) + strconv.Itoa(int(message.MsgStatus)), //消息ID
		},
	)
	if err != nil {
		logrus.Error(">>> MQ发送消息到Queue["+config.MqDataSave.QueueName+"] 失败. ", err)
		return
	}
}

func (mq MQProducer) ToPersist(message model.ChatMessage) {
	messageJson, _ := json.Marshal(message) //序列化为json
	logrus.Info(">>> MQ发送消息到Queue["+config.MqDataSave.QueueName+"] ... message = ", string(messageJson))

	err := config.GetMqChannel().Publish(config.MqDataSave.Exchange, config.MqDataSave.RoutingKey, false, false,
		amqp.Publishing{
			ContentType:  "application/json",                // 消息内容的类型
			Body:         messageJson,                       // 消息内容
			DeliveryMode: amqp.Persistent,                   // 消息持久化
			MessageId:    strconv.FormatInt(message.Id, 10), //消息ID
		},
	)
	if err != nil {
		logrus.Error(">>> MQ发送消息到Queue["+config.MqDataSave.QueueName+"] 失败. ", err)
		return
	}
}

func (mq MQProducer) ToOfflineTable(message *model.ChatMessage) {
	messageJson, _ := json.Marshal(message) //序列化为json
	logrus.Info(">>> MQ发送消息到Queue["+config.MqDataOffline.QueueName+"] ... message = ", string(messageJson))

	config.GetMqChannel().Publish(config.MqDataOffline.Exchange, config.MqDataOffline.RoutingKey, false, false,
		amqp.Publishing{
			ContentType:  "application/json",                // 消息内容的类型
			Body:         messageJson,                       // 消息内容
			DeliveryMode: amqp.Persistent,                   // 消息持久化
			MessageId:    strconv.FormatInt(message.Id, 10), //消息ID
		},
	)
}
